﻿Imports System.Data
Imports VSModel
Imports Cls_Common
Imports SecurityService

Partial Class Control_Formula_Edit
    Inherits System.Web.UI.UserControl
    Private Shared ReadOnly log As log4net.ILog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
    Private strPlayerUrl As String
    Private strFileUrl As String
    Private strImageUrl As String
#Region "Property"
    Public Property PlayerUrl() As String
        Get
            Return strPlayerUrl
        End Get
        Set(ByVal Value As String)
            strPlayerUrl = Value
        End Set
    End Property
    Public Property FileUrl() As String
        Get
            Return strFileUrl
        End Get
        Set(ByVal Value As String)
            strFileUrl = Value
        End Set
    End Property
    Public Property ImageUrl() As String
        Get
            Return strImageUrl
        End Get
        Set(ByVal Value As String)
            strImageUrl = Value
        End Set
    End Property
#End Region
#Region "Sub and Function "
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            If Not Request.QueryString("Id") Is Nothing Then
                txtCost.Attributes.Add("onblur", "return CheckMoneyFormat('" + txtCost.ClientID + "');")
                txtPortion.Attributes.Add("onblur", "return CheckMoneyFormat('" + txtPortion.ClientID + "');")
                txtTimepreparing.Attributes.Add("onblur", "return CheckMoneyFormat('" + txtTimepreparing.ClientID + "');")
                txtTimetocook.Attributes.Add("onblur", "return CheckMoneyFormat('" + txtTimetocook.ClientID + "');")
                LoadFormulaType()
                hidID.Value = Request.QueryString("Id")
                ShowData()
            End If
            Dim script As ScriptManager = ScriptManager.GetCurrent(Me.Page)
            If Not script Is Nothing AndAlso script.IsInAsyncPostBack Then
                ScriptManager.RegisterStartupScript(Me.Page, Me.Page.GetType, "duyjs", "ajaxJquery()", True)
            Else
                Me.Page.ClientScript.RegisterStartupScript(Me.Page.GetType(), "duyjs", String.Concat("Sys.Application.add_load(function(){", "ajaxJquery()", "});"), True)
            End If
            Dim ctrl As System.Web.UI.WebControls.WebControl
            ctrl = txtMaterial.CreateCommandButton("ask_mask_fullname", "remove_format.gif", "Bỏ định dạng")
            ctrl.Attributes("onclick") = "removeTextFormat('" + txtMaterial.ClientID + "');"
            'get the pos after the Italic    
            Dim pos As Integer
            pos = txtMaterial.ToolControls.IndexOf("JustifyRight") + 1
            'add this custom button into the editor    
            txtMaterial.InsertToolControl(pos, "ask_mask_fullname", ctrl)
        End If
    End Sub
    Protected Sub LoadFormulaType()
        Using data As New VSEntities
            Dim p = (From q In data.FormulaTypes Order By q.Id Descending Select q).ToList()
            ddlFormulaType.DataSource = p
            ddlFormulaType.DataTextField = "Title"
            ddlFormulaType.DataValueField = "Id"
            ddlFormulaType.DataBind()
        End Using
    End Sub
    Protected Sub ShowData()
        Using data As New VSEntities
            Dim p As Formula = (From q In data.Formulae Where q.Id = hidID.Value).SingleOrDefault
            If Not p Is Nothing Then
                Dim strImageBig As String = ""
                chkIsHot.Checked = IIf(IsNothing(p.IsHot) = True, False, p.IsHot)
                ckbIsNew.Checked = IIf(IsNothing(p.IsNew) = True, False, p.IsNew)
                If p.IsHot = True Then
                    hidImageBig.Text = IIf(IsNothing(p.ImageBig) = True, "", p.ImageBig)
                    strImageBig += "Change_Hot();showImageBig('" + IIf(IsNothing(p.ImageBig) = True, "", p.ImageBig) + "');"
                End If
                hidImageBig.Text = IIf(IsNothing(p.ImageBig) = True, "", p.ImageBig)

                p.ImageBig = hidImageBig.Text.Trim
                txtTitle.Text = IIf(IsNothing(p.Title) = True, "", p.Title)
                hidTitle.Value = IIf(IsNothing(p.Title) = True, "", p.Title)
                txtDescription.Text = IIf(IsNothing(p.Description) = True, "", p.Description)
                txtMaterial.Text = IIf(IsNothing(p.Material) = True, "", p.Material)
                'Lay nhung nguyen lieu trong bang quan he tuong ung voi id nay
                Dim strMaterial As String = ""
                Dim strMaterialValue As String = ""
                Dim pMaterial = (From q In data.FormulaMaterials Where q.FormulaId = hidID.Value Select q).ToList
                If pMaterial.Count > 0 Then
                    For i As Integer = 0 To pMaterial.Count - 1
                        strMaterial = strMaterial & pMaterial(i).Material.Title & "; "
                        strMaterialValue = strMaterialValue & pMaterial(i).MaterialId & "; "
                    Next
                End If
                txtMaterialSelect.Text = strMaterial.Trim()
                hidMaterial.Value = strMaterialValue.Trim()

                txtWaytocook.Text = IIf(IsNothing(p.WayToCook) = True, "", p.WayToCook)
                'Lay nhung cach thuc hien trong bang quan he tuong ung voi id nay
                Dim strWayToCook As String = ""
                Dim strWayToCookValue As String = ""
                Dim pWayToCook = (From q In data.FormulaWayToCooks Where q.FormulaId = hidID.Value Select q).ToList
                If pWayToCook.Count > 0 Then
                    For i As Integer = 0 To pWayToCook.Count - 1
                        strWayToCook = strWayToCook & pWayToCook(i).WayToCook.Title & "; "
                        strWayToCookValue = strWayToCookValue & pWayToCook(i).WayToCookId & "; "
                    Next
                End If
                txtWayToCookSelect.Text = strWayToCook.Trim()
                hidWayToCook.Value = strWayToCookValue.Trim()
                If (p.IsYoutube = True) Then
                    drlSourceVideo.SelectedIndex = 1
                    txtVideourl.Text = p.URL
                ElseIf (p.IsYoutube = False) Then
                    drlSourceVideo.SelectedIndex = 2
                    hplvideo.Text = IIf(IsNothing(p.URL) = True, "", p.URL)
                    hidVideoPath.Text = IIf(IsNothing(p.URL) = True, "", p.URL)
                End If
                hidImagePath.Text = IIf(IsNothing(p.Image) = True, "", p.Image)
                imgUpload.ImageUrl = IIf(IsNothing(p.Image) = True, "", p.Image)
                ddlFormulaType.SelectedValue = IIf(IsNothing(p.FormulaTypeId) = True, "", p.FormulaTypeId)
                txtFastconduct.Text = IIf(IsNothing(p.FastConduct) = True, "", p.FastConduct)
                If Not p.Portion Is Nothing Then
                    txtPortion.Text = FormatCurrency(IIf(IsNothing(p.Portion) = True, "", p.Portion))
                End If
                If Not p.TimePreparing Is Nothing Then
                    txtTimepreparing.Text = FormatCurrency(IIf(IsNothing(p.TimePreparing) = True, "", p.TimePreparing))
                End If
                If Not p.TimeToCook Is Nothing Then
                    txtTimetocook.Text = FormatCurrency(IIf(IsNothing(p.TimeToCook) = True, "", p.TimeToCook))
                End If
                If Not p.Cost Is Nothing Then
                    txtCost.Text = FormatCurrency(IIf(IsNothing(p.Cost) = True, "", p.Cost))
                End If
                txtDateontv.Text = IIf(IsNothing(p.DateOnTV) = True, "", Convert.ToDateTime(p.DateOnTV).ToString("dd/MM/yyyy"))
                'Hien thi clip
                If p.IsYoutube = True Then
                    Dim baseUrl As String = Request.Url.GetLeftPart(UriPartial.Authority)
                    divEmbededVideo.Visible = False
                    divFileYoutube.Visible = True
                    ' divFileYoutube.InnerHtml = p.URL
                    ltrShow.Text = p.URL
                    'FileUrl() = SplitVideoYoutube(p.URL)
                    'ImageUrl() = baseUrl + ResolveUrl_Video(p.Image)
                Else
                    divEmbededVideo.Visible = True
                    divFileYoutube.Visible = False
                    Dim baseUrl As String = Request.Url.GetLeftPart(UriPartial.Authority)
                    PlayerUrl() = baseUrl + ResolveUrl_Video("~/jwplayer/player.swf")
                    FileUrl() = p.URL
                    ImageUrl() = p.Image
                End If
                'Show keyword
                Dim obj = (From ck In data.FormulaKeywords Join k In data.Keywords On ck.KeywordId Equals k.KeywordID Where ck.FormulaId = p.Id Order By k.Keyword1 Ascending Select New With {.KeyId = ck.KeywordId, .KeyWord = k.Keyword1}).ToList
                For i As Integer = 0 To obj.Count - 1
                    txtKeyword.Text &= obj(i).KeyId & ";"
                    txtStrKeyWord.Text &= obj(i).KeyWord & ";"
                Next

                'Show Subject
                Dim s = (From cs In data.FormulaSubjects Join sb In data.Subjects On cs.SubjectId Equals sb.SubjectId Where cs.FormulaId = p.Id Order By sb.Subject1 Ascending Select New With {.KeyId = cs.SubjectId, .Subject = sb.Subject1}).FirstOrDefault
                If (Not s Is Nothing) Then
                    txtSubjectId.Text = s.KeyId & ";"
                    txtSubject.Text = s.Subject & ";"
                End If

                Excute_Javascript("" + strImageBig + "appendOptionLast('" & txtKeyword.Text & "','" & txtStrKeyWord.Text & "','selKeyWord');", Me.Page, True)
            End If
        End Using
    End Sub
    Protected Function SplitVideoYoutube(ByVal strUrl As String) As String
        Dim intStart As Integer = strUrl.IndexOf("=")
        Dim intEnd As Integer = strUrl.IndexOf("&")
        Dim scr As String = strUrl.Substring(intStart + 1, strUrl.Length - intStart - 1)
        Return scr
    End Function
    Public Function ResolveUrl_Video(ByVal url As String) As String
        If url Is Nothing Then
            Return ""
        End If
        If url.Length = 0 Then
            Return ""
        End If

        ' there is no ~ in the first character position, just return the url 
        If url(0) <> "~"c Then
            Return url
        End If

        Dim applicationPath As String = HttpContext.Current.Request.ApplicationPath

        ' there is just the ~ in the URL, return the applicatonPath 
        If url.Length = 1 Then
            Return applicationPath
        End If

        ' assume url looks like ~somePage 
        Dim indexOfUrl As Integer = 1

        ' determine the middle character 
        Dim midPath As String = If((applicationPath.Length > 1), "/", String.Empty)

        ' if url looks like ~/ or ~\ change the indexOfUrl to 2 
        If url(1) = "/"c OrElse url(1) = "\"c Then
            indexOfUrl = 2
        End If

        Return applicationPath & midPath & url.Substring(indexOfUrl)
    End Function
#End Region
#Region "Event for control"
    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
        Using data As New VSEntities
            'Kiem tra trung tieu de
            If hidTitle.Value.Trim <> txtTitle.Text.Trim() Then
                Dim Title As String = txtTitle.Text.Trim()
                Dim pCheck = (From qCheck In data.Formulae Where qCheck.Title = Title Select qCheck).ToList()
                If pCheck.Count > 0 Then
                    Excute_Javascript("Alertbox('Tiêu đề công thức này đã tồn tại, vui lòng nhập tiêu đề công thức khác.');", Me.Page, True)
                    Return
                End If
            End If
            Dim p As Formula = (From q In data.Formulae Where q.Id = hidID.Value).SingleOrDefault
            Dim sTitle As String = p.Title
            Dim sQueryString As String = p.QueryString
            Try
                p.Id = hidID.Value
                p.Title = txtTitle.Text.Trim()
                p.QueryString = makeURLFriendly(txtTitle.Text.Trim())
                p.Description = txtDescription.Text.Trim()
                p.Material = txtMaterial.Text.Trim()
                p.WayToCook = txtWaytocook.Text.Trim()
                'p.URLClip = txtUrlclip.Text.Trim()
                p.Image = hidImagePath.Text.ToString
                If drlSourceVideo.SelectedValue = 1 Then
                    p.IsYoutube = True
                    p.URL = txtVideourl.Text
                ElseIf drlSourceVideo.SelectedValue = 2 Then
                    p.IsYoutube = False
                    p.URL = hidVideoPath.Text
                ElseIf drlSourceVideo.SelectedValue = 0 Then
                    p.IsYoutube = Nothing
                    p.URL = ""
                End If
                p.FormulaTypeId = ddlFormulaType.SelectedValue.Trim()
                p.FastConduct = txtFastconduct.Text.Trim()
                If txtPortion.Text = "" Then
                    p.Portion = Nothing
                Else
                    p.Portion = Int32.Parse(txtPortion.Text.Trim().Replace(",", ""))
                End If
                If txtTimepreparing.Text = "" Then
                    p.TimePreparing = Nothing
                Else
                    p.TimePreparing = Double.Parse(txtTimepreparing.Text.Trim().Replace(",", ""))
                End If
                If txtTimetocook.Text = "" Then
                    p.TimeToCook = Nothing
                Else
                    p.TimeToCook = Double.Parse(txtTimetocook.Text.Trim().Replace(",", ""))
                End If
                'p.Portion = IIf(txtPortion.Text = "", Nothing, Integer.Parse(txtPortion.Text.Trim()))
                'p.TimePreparing = IIf(String.IsNullOrEmpty(txtTimepreparing.Text.Trim) = True, Nothing, Double.Parse(txtTimepreparing.Text.Trim()))
                'p.TimeToCook = IIf(String.IsNullOrEmpty(txtTimetocook.Text.Trim), Nothing, Double.Parse(txtTimetocook.Text.Trim()))
                If txtCost.Text <> "" Then
                    Dim Cost As Double = Double.Parse(txtCost.Text.Trim())
                    p.Cost = Cost
                Else
                    p.Cost = Nothing
                End If
                p.Modified = Now()
                p.Modifier = Session("Username")
                p.DateOnTV = StringToDate(txtDateontv.Text.Trim())
                p.Subject = txtSubject.Text.Trim
                p.Keyword = txtKeyword.Text.Trim
                p.IsHot = chkIsHot.Checked
                p.IsNew = ckbIsNew.Checked
                If p.IsHot = True Then
                    p.ImageBig = hidImageBig.Text.Trim
                End If
                data.SaveChanges()
                'Them vao bang FormulaMaterial
                If hidMaterial.Value <> "" Then
                    DeleteFormulaMaterial(hidID.Value)
                    Dim arrMaterial As String() = hidMaterial.Value.Split(";")
                    arrMaterial = ConverString(arrMaterial)
                    For i As Integer = 0 To arrMaterial.Length - 2
                        Dim Result As Integer = SaveFormulaMaterial(Int32.Parse(arrMaterial(i)), hidID.Value)
                        If Result = 0 Then
                        End If
                    Next
                End If
                'Them vao bang FormulaWayToCook
                If hidWayToCook.Value <> "" Then
                    DeleteFormulaWayToCook(hidID.Value)
                    Dim arrWayToCook As String() = hidWayToCook.Value.Split(";")
                    arrWayToCook = ConverString(arrWayToCook)
                    For i As Integer = 0 To arrWayToCook.Length - 2
                        Dim Result As Integer = SaveFormulaWayToCook(Int32.Parse(arrWayToCook(i)), hidID.Value)
                        If Result = 0 Then
                        End If
                    Next
                End If
                'Delete keyword
                Dim obj = (From ck In data.FormulaKeywords Where ck.FormulaId = p.Id Select ck).ToList
                If (Not obj Is Nothing AndAlso obj.Count > 0) Then
                    For i As Integer = 0 To obj.Count - 1
                        Dim iCid As Integer = obj(i).FormulaId
                        Dim iKid As Integer = obj(i).KeywordId
                        Dim o = (From cok In data.FormulaKeywords Where cok.FormulaId = iCid And cok.KeywordId = iKid Select cok).FirstOrDefault
                        data.FormulaKeywords.DeleteObject(o)
                        data.SaveChanges()
                    Next
                End If
                RemoveKeyWordJavascript(sTitle)
                RemoveKeyWordJavascript(sQueryString)

                'Insert keyword
                Dim arrKeyWord As String() = txtKeyword.Text.TrimEnd(";").Split(";")
                If arrKeyWord.Length > 1 Then
                    For i As Integer = 0 To arrKeyWord.Length - 1
                        Dim kw As New FormulaKeyword
                        kw.FormulaId = hidID.Value
                        kw.KeywordId = arrKeyWord(i)
                        data.FormulaKeywords.AddObject(kw)
                    Next
                    data.SaveChanges()
                End If
                AddKeyWordJavascript(txtTitle.Text)
                AddKeyWordJavascript(makeURLFriendly(txtTitle.Text.Trim))

                'Delete Subject of contents
                Dim objS = (From s In data.FormulaSubjects Where s.FormulaId = p.Id Select s).FirstOrDefault
                If (Not objS Is Nothing) Then
                    data.FormulaSubjects.DeleteObject(objS)
                    data.SaveChanges()
                End If

                'Insert Subject
                If Not String.IsNullOrEmpty(txtSubject.Text.Trim) Then
                    Dim q As New FormulaSubject
                    q.FormulaId = hidID.Value
                    q.SubjectId = txtSubjectId.Text.Trim.TrimEnd(";")
                    data.FormulaSubjects.AddObject(q)
                    data.SaveChanges()
                End If
                Insert_App_Log("Edit Formula:" & txtTitle.Text.Trim & "", Function_Name.Formula, Audit_Type.Edit, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))
                Excute_Javascript("Alertbox('Cập nhật dữ liệu thành công.');window.location ='../../Page/Formula/List.aspx';", Me.Page, True)
            Catch ex As Exception
                log4net.Config.XmlConfigurator.Configure()
                log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
                Excute_Javascript("Alertbox('Cập nhật thất bại.');", Me.Page, True)
            End Try
        End Using
    End Sub
    'Chuyen thanh chuoi phan biet
    Protected Function ConverString(ByVal str As String()) As String()
        For i As Integer = 0 To str.Length - 2
            If CheckValueExists(str, str(i)) = 0 Then
                For j As Integer = i To str.Length - 2
                    str(j) = str(j + 1)
                Next
            End If
        Next
        Return str
    End Function
    'Kiem tra gia tri nay da ton tai chua
    Protected Function CheckValueExists(ByVal str As String(), ByVal intValue As Integer) As Integer
        Dim Result As Integer = 0
        For i As Integer = 0 To str.Length - 2
            If Int32.Parse(str(i)) = intValue Then
                Result = 1
                Exit For
            End If
        Next
        Return Result
    End Function
    'Xoa công thức
    Protected Sub DeleteFormula(ByVal ID As Integer)
        Using data As New VSEntities
            Try
                Dim p = From q In data.Formulae Where q.Id = ID Select q
                For Each oder In p
                    data.Formulae.DeleteObject(oder)
                Next
                data.SaveChanges()
                Excute_Javascript("Alertbox('Thêm công thức thất bại.');", Me.Page, True)
            Catch ex As Exception
            End Try
        End Using

    End Sub
    'Luu ban quan he giua công thức và nguyên liệu
    Protected Function SaveFormulaMaterial(ByVal MaterialId As Integer, ByVal FormulaId As Integer) As Integer
        Dim Result As Integer = 0
        Using data As New VSEntities
            Try
                Dim context As New FormulaMaterial
                context.FormulaId = FormulaId
                context.MaterialId = MaterialId
                data.AddToFormulaMaterials(context)
                data.SaveChanges()
                Result = 1
            Catch ex As Exception
                Result = 0
            End Try
        End Using
        Return Result
    End Function
    'Luu ban quan he giua công thức và cach thuc hien
    Protected Function SaveFormulaWayToCook(ByVal WayToCookId As Integer, ByVal FormulaId As Integer) As Integer
        Dim Result As Integer = 0
        Using data As New VSEntities
            Try
                Dim context As New FormulaWayToCook
                context.FormulaId = FormulaId
                context.WayToCookId = WayToCookId
                data.AddToFormulaWayToCooks(context)
                data.SaveChanges()
                Result = 1
            Catch ex As Exception
                Result = 0
            End Try
        End Using
        Return Result
    End Function
    'Xoa bang quan he FormulaMaterial
    Protected Sub DeleteFormulaMaterial(ByVal Id As Integer)
        Using Data As New VSEntities
            Try
                Dim p = From q In Data.FormulaMaterials Where q.FormulaId = Id Select q
                For Each oder In p
                    Data.FormulaMaterials.DeleteObject(oder)
                Next
                Data.SaveChanges()
            Catch ex As Exception
            End Try
        End Using
    End Sub
    'Xoa bang quan he FormulaWayToCook
    Protected Sub DeleteFormulaWayToCook(ByVal Id As Integer)
        Using Data As New VSEntities
            Try
                Dim p = From q In Data.FormulaWayToCooks Where q.FormulaId = Id Select q
                For Each oder In p
                    Data.FormulaWayToCooks.DeleteObject(oder)
                Next
                Data.SaveChanges()
            Catch ex As Exception
            End Try
        End Using
    End Sub
    Protected Sub hplSelKeyWord_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles hplSelKeyWord.Init
        hplSelKeyWord.CssClass = "thickbox"
        hplSelKeyWord.NavigateUrl = "~/Page/KeyWord/KeyWord.aspx?keepThis=true&TB_iframe=true&height=400&width=350&modal=true"
    End Sub

    Protected Sub hplSelSubject_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles hplSelSubject.Init
        hplSelSubject.CssClass = "thickbox"
        hplSelSubject.NavigateUrl = "~/Page/Subject/Subject.aspx?keepThis=true&TB_iframe=true&height=400&width=400&modal=true"
    End Sub
    Protected Sub hplMaterial_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles hplMaterial.Init
        hplMaterial.CssClass = "thickbox"
        hplMaterial.NavigateUrl = "~/Page/Formula/MaterialSelect.aspx?keepThis=true&TB_iframe=true&height=400&width=350&modal=true"
    End Sub

    Protected Sub hplWayToCook_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles hplWayToCook.Init
        hplWayToCook.CssClass = "thickbox"
        hplWayToCook.NavigateUrl = "~/Page/Formula/WayToCookSelect.aspx?keepThis=true&TB_iframe=true&height=400&width=350&modal=true"
    End Sub
#End Region

    Protected Sub btnHuy_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnHuy.Click
        Response.Redirect("List.aspx")
    End Sub
End Class
